package com.powernode.filter;

import javax.annotation.Resource;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.BussinessEnum;
import com.powernode.constant.HttpConstants;
import com.powernode.model.Result;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import com.powernode.config.WhiteUrlConfig;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;


import java.util.Date;

/**
 * 全局token过滤器
 * 前后端约定好的令牌存放，请求头的Authorization Bearer token
 */
@Component
@Slf4j
public class AuthFIlter implements GlobalFilter,Ordered {
    
    
    @Resource
    private WhiteUrlConfig whiteUrlConfig;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public int getOrder() {
        
        return -5;
    }

    /**
     * 校验token
     * 1获取请求路径
     * 2判断路径是否可以放行，白名单
     * 放行就不需要验证
     * 不放行，需要对身份进行验证
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径
        String path = request.getPath().toString();
        //判断当前路径是否需要放行，白名单
        if(whiteUrlConfig.getAllowUrl().contains(path)){
            //如果在白名单里面,放行
            return chain.filter(exchange);
        }
        //不在白名单里面，对身份进行认证.从请求头里面获取token
        String authorization = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);
        //判断token是否有值
        if(StringUtils.hasText(authorization)){
            String token = authorization.replaceFirst(AuthConstants.BEARER, "");
            //判断token是否存在且在redis里面
            if(StringUtils.hasText(token) && stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX + token)){
                //身份验证通过，放行
                return chain.filter(exchange);
            }

        }

        //流程到这，说明验证身份没有通过
        log.error("拦截非法请求，时间：{},请求API:{}",new Date(),path);
        //获取相应对象
        ServerHttpResponse response = exchange.getResponse();
        //相应头信息
        response.getHeaders().set(HttpConstants.CONTENT_TYPE, HttpConstants.APPLICATION_JSON);
        //设置返回相应消息
        Result<Object> result = Result.fali(BussinessEnum.UN_AUTHORIZATION);

        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = null;
        try {
            bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));

    }

}
